package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderLogisticsService;
import com.hmall.order.service.IOrderService;
import com.hmall.order.vo.ResultParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private IOrderLogisticsService orderLogisticsService;


    @Override
    public Long getOrder(ResultParams params) {

        //根据itemId查询商品信息
        Item item = itemClient.QueryById(params.getItemId());
        //基于商品价格、购买数量计算商品总价：totalFee
        Long price = item.getPrice();
        Order order=new Order();
        order.setTotalFee(price*params.getNum());

        //封装Order对象，初始status为未支付
        order.setStatus(1);
        order.setPaymentType(params.getPaymentType());
//        order.setUserId();
        Address address = userClient.findAddressById(params.getAddressId());
        Long userId = address.getUserId();
        order.setUserId(userId);


        //将Order写入数据库tb_order表中
        this.save(order);

        //将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
//        orderDetailService.getOrderDetail(params);
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setItemId(params.getItemId());
        orderDetail.setNum(params.getNum());
        orderDetail.setName(item.getName());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setImage(item.getImage());
        orderDetail.setOrderId(order.getId());
        orderDetailService.save(orderDetail);

        //将地址封装为OrderLogistics对象，写入tb_order_logistics表
//        orderLogisticsService.getOrderLogistics(params);
        OrderLogistics orderLogistics=new OrderLogistics();
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setMobile(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setStreet(address.getStreet());
        orderLogistics.setTown(address.getTown());
        orderLogisticsService.save(orderLogistics);

        return order.getId();
    }
}
